package com.kzj.common.config;

import com.kzj.common.exception.ExceptionEnum;
import com.kzj.common.exception.SystemException;
import com.kzj.common.log.Logger;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigProperties {
    private static String defaultConfigPath="config.properties";
    static private  Properties properties;
    static {
        properties=new Properties();
        try(InputStream defaultConfig=ConfigProperties.class.getClassLoader().getResourceAsStream(defaultConfigPath)) {
            properties.load(defaultConfig);
            Logger.info(String.format("默认配置文件： %s，加载成功",defaultConfigPath));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    static public void add(String configPath){
        try(FileInputStream config=new FileInputStream(configPath)) {
            properties.load(config);
            Logger.info(String.format("配置文件： %s，加载成功",configPath));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    static public String get(String key){
        if(properties==null){
            throw new SystemException(ExceptionEnum.CONFIG_NOT_LOAD);
        }
        return properties.getProperty(key);
    }
    static public String get(String key,String defaultVal){
        if(properties==null){
            throw new SystemException(ExceptionEnum.CONFIG_NOT_LOAD);
        }
        return properties.getProperty(key,defaultVal);
    }
    static public  String mustGet(String key){
        if(properties==null){
            throw new SystemException(ExceptionEnum.CONFIG_NOT_LOAD);
        }
        String val=properties.getProperty(key);
        if(val==null)
            throw new SystemException(ExceptionEnum.CONFIG_PROPERTIES_MISS);
        return val;
    }
}
